package cn.youruan.demo.filter;

import cn.youruan.demo.common.BaseContext;
import cn.youruan.demo.common.R;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否登录
 */
@Slf4j
@WebFilter(filterName = "LoginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {

    //定义一个路径匹配器,支持通配符
    private static final AntPathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取用户本次请求的uri;
        String URI= request.getRequestURI();
        log.info("拦截到请求: {}",URI);
        //2.判断用户发送的这个请求是否需要拦截
        String[] urls= new String[]{
              //这几个请求都不需要拦截,直接放行
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",//移动端发送短信
                "/user/login",
                "/user/register",
                "/user/phoneLogin",
                "/user/consumeCount",
                "/user/*",
                "/publicInformation/*",
                "/file/*",
                "/hobby/*"
        };

        boolean check = check(urls, URI);
        //3.如果不需要处理直接放行
        if (check) {
            log.info("本次请求{}不需要处理",URI);
            filterChain.doFilter(request,response);
            return;
        }
        //4.如果需要处理
       if (request.getSession().getAttribute("employee") !=null) {
           //已经登录,直接放行

           Long empId = (Long) request.getSession().getAttribute("employee");
           log.info("用户已登录,id为{}",empId);

           BaseContext.setCurrentId(empId);

           filterChain.doFilter(request,response);
           return;
       }

       //判断移动端用户登录状态
        if (request.getSession().getAttribute("user") !=null) {
            //已经登录,直接放行
            Long userId = (Long) request.getSession().getAttribute("user");
            log.info("用户已登录,id为{}",userId);

            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response);
            return;
        }

        //5. 如果需要登录但没有登录,打回登录页面
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 路径匹配,检查本次请求是否需要放行
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = pathMatcher.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
